package org.chronologger.poppaea.client.widgets;

import java.util.Date;

import org.chronologger.poppaea.client.Chronology;
import org.chronologger.poppaea.client.PositionResolver;
import org.chronologger.poppaea.client.WidgetCache;
import org.chronologger.poppaea.client.WidgetCache.WidgetFactory;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.TimeZone;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;

import static org.chronologger.poppaea.client.Chronology.*;

public class TimelineWidget extends Composite {

	protected static final WidgetFactory<Label> LabelFactory = new WidgetFactory<Label>() {

		public Label make() {
			return new Label();
		}
	};
	
	protected static final TimeZone timeZone = TimeZone.createTimeZone(0);
	protected final AbsolutePanel timelinePanel = new AbsolutePanel();
	protected final Chronology owner;
	protected final WidgetCache<Label> timelineMarkers = new WidgetCache<Label>(
			LabelFactory, timelinePanel, "timeline-marker");
	protected final WidgetCache<Label> timelineDaysMarkers = new WidgetCache<Label>(
			LabelFactory, timelinePanel, "timeline-day-marker");

	public TimelineWidget(Chronology owner) {
		this.owner = owner;
		
		timelinePanel.setSize("100%", "100%");
		initWidget(timelinePanel);
	}
	
	public void update() {
		// length of the timeline (in milliseconds)
		Long milliSeconds = owner.getEndtime().getTime() - owner.getStarttime().getTime();
		// length of the timeline (in days)
		int days = (int) ((milliSeconds + 43200000) / 86400000 + 1);
		// one marker per 100 px
		final PositionResolver positionResolver = owner.getPositionResolver();
		int markerCount = days * positionResolver.getPreferredResolution() / 100;

		timelineMarkers.setCapacity(markerCount);
		timelineDaysMarkers.setCapacity(days + 1);

		// Formatters for timeline labels
		DateTimeFormat fmtDays = DateTimeFormat.getFormat("dd.MM.yyyy");
		DateTimeFormat fmt = DateTimeFormat.getFormat("HH:mm:ss");

		// update labels
		int position = 0;
		int daynum = 0;
		String previousDay = "";
		for (Label l : timelineMarkers) {
			timelinePanel.setWidgetPosition(l, position, 15);
			Date date = new Date(positionResolver.getTime(position));

			l.setText(fmt.format(date, timeZone));
			String dayStr = fmtDays.format(date);
			
			// "a new day"?
			if (!previousDay.equals(dayStr)) {
				Label day = timelineDaysMarkers.get(daynum);
				timelinePanel.setWidgetPosition(day, position, 0);
				day.setText(dayStr);
				daynum++;
				previousDay = dayStr;
			}

			// go to next label position
			position += 100;
		}

		// update size
		setWidth(position + "px");
		setHeight(TIMELINE_PANEL_HEIGHT + "px");
	}
	
}